
#include <errno.h>
#include <sys/uio.h>
#include <memory>

#include "Buffer.hpp"
#include "SocketsOps.hpp"

namespace tulun
{
    // class Buffer
    // static const size_t kCheapPrepend = 8;
    // static const size_t kInitialSize = 1024;
    static const char kCRLF[] = "\r\n";

    // std::vector<char> buffer_;
    // size_t readerIndex_; // 可读数据首地址
    // size_t writerIndex_; // 可写数据首地址

    ssize_t Buffer::readFd(int fd, int *savedError)
    {
        char extrabuf[65536]; // 64k
        // std::unique_ptr<char[]> extrabuf(new char[65536]);
        struct iovec vec[2];

        const size_t writable = writableBytes();
        vec[0].iov_base = begin() + writerIndex_;
        vec[0].iov_len = writable;
        vec[1].iov_base = extrabuf;
        vec[1].iov_len = sizeof(extrabuf);
        const int iovcnt = (writable < sizeof extrabuf) ? 2 : 1;
        const ssize_t n = Sockets::readv(fd, vec, iovcnt);
        if (n < 0)
        {
            *savedError = errno;
        }
        else if (static_cast<size_t>(n) <= writable)
        {
            writerIndex_ += n;
        }
        else
        {
            writerIndex_ = buffer_.size();
            append(extrabuf, n - writable);
        }
    }

} // namespace tulun